package cn.org.donald.framework.service.impl;

import cn.org.donald.framework.service.SysLoginService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.org.donald.framework.util.BeanUtil;
import cn.org.donald.mapper.LoginMapper;
import cn.org.donald.pojo.entity.system.Login;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;



/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Donald
 * @since 2020-11-16
 */
@Service(interfaceClass = SysLoginService.class, version = "1.0.0",group = "donald")
public class SysLoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements SysLoginService {

    @Autowired
    private LoginMapper loginMapper;


    /**
     * 保存用户登录信息
     * @param login
     * @return
     */
    @Override
    public boolean saveLoginInfo(Login login) {

        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",login.getUserId());
        Login loginFromDb = loginMapper.selectOne(queryWrapper);

        Login insertLogin = new Login();
        insertLogin.setUserId(login.getUserId());
        insertLogin.setIpLogin(login.getIpLogin());
        insertLogin.setAuthorization(login.getAuthorization());

        if (BeanUtil.isEmptyOrClassFieldAllEmpty(loginFromDb)){
            int insert = loginMapper.insert(insertLogin);
            return insert > 0;
        }
        insertLogin.setGmtLastLogin(loginFromDb.getGmtModified());
        insertLogin.setIpLastLogin(loginFromDb.getIpLogin());
        insertLogin.setId(loginFromDb.getId());
        int i = loginMapper.updateById(insertLogin);
        return i > 0;
    }

    @Override
    public Login getLoginRecord(Long userId) {
        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return super.getOne(queryWrapper);
    }

    @Override
    public String findAuthorizationByUserId(Long id) {
        return loginMapper.selectAuthorizationByUserId(id);
    }
}
